<?
/**
 * This file is part of XNAT light.
 *
 * XNAT light is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * XNAT light is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with XNAT light.  If not, see <http://www.gnu.org/licenses/>.
 */
namespace NRG\Framework\Models;

use NRG\Framework\Exceptions\MalformedXMLException as MalformedXMLException;
use NRG\Framework\Exceptions\IllegalArgumentException as IllegalArgumentException;

/**
 * XML model
 *
 * @package NRG\Framework\Models
 */
class XML
{
    /**
     * Contains XML object
     *
     * @var \SimpleXMLElement
     */
    protected $_xml;

    /**
     * Constructor
     *
     * @param string $xml
     */
    public function __construct($xml)
    {
	if(!is_string($xml))
	    throw new IllegalArgumentException("XML must be a string");

	if($xml == "")
	    throw new IllegalArgumentException("XML cannot be empty");

	$this->load($xml);
    }

    /**
     * Load XML into a SimpleXMLElement
     *
     * @param string $xml
     * @throws MalformedXMLException
     */
    public function load($xml)
    {
	if(!$this->_xml = @simplexml_load_string($xml))
	    throw new MalformedXMLException($xml);
    }

    /**
     * Retrieve XML as a SimpleXMLElement
     *
     * @return \SimpleXMLElement
     */
    public function asSimpleXml()
    {
	return $this->_xml;
    }

    /**
     * Retrieve XML as a string
     *
     * @return string
     */
    public function asString()
    {
	return $this->_xml->asXML();
    }

    /**
     * To string method
     *
     * @return string
     */
    public function __toString()
    {
	return $this->_xml->asXML();
    }
}
